package com.learn.training.multithread.chapter9.demo1;


import java.util.concurrent.CompletableFuture;

public class Demo {
    public static void main(String[] args) throws InterruptedException {
        //创建异步执行任务
        CompletableFuture<Double> cf = CompletableFuture.supplyAsync(Demo::fetchPrice);

        // 如果执行成功，则打印结果
        cf.thenAccept((result) -> {
            System.out.println("Price: " + result);
        });

        // 如果执行失败，则打印异常
        cf.exceptionally((e) -> {
            e.printStackTrace();
            return null;
        });

        // 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:
        Thread.sleep(2000);

    }

    static Double fetchPrice() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if(Math.random() < 0.1) {
            throw new RuntimeException("fetch price failed!");
        }
        return 5 + Math.random() * 10;
    }
}
